package com.khstudio.filebrowser.duallist;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.khstudio.filebrowser.duallist.KhFileBrowserAdapter.SELECT;
import com.khstudio.filebrowser.duallist.KhFileBrowserItem.TYPE;
import com.khstudio.filebrowser.util.KhExternalStorage;
import com.khstudio.filebrowser.util.KhLog;

public class KhFileBrowserView extends ListView {
    private static final int                FLAG_FOLDER_UP  = 0x0001;
    private static final int                FLAG_FOLDER     = 0x0002;
    private static final int                FLAG_FILE       = 0x0004;

    private Context                         mContext;
    private onFileBrowserListener           mListener;

    private ArrayList<KhFileBrowserItem>    mList;
    private KhFileBrowserAdapter            mAdapter;

    private String              mSdCard;
    private String              mExtsdCard;
    private String              mRoot;

    private int                 mSelectCnt;
    private int                 mSelectMax;

    public interface onFileBrowserListener {
        void onUpdate();
        void onClick(KhFileBrowserItem item);
    }

    public KhFileBrowserView(Context context) {
        this(context, null);
    }

    public KhFileBrowserView(Context context, AttributeSet attrs) {
        this(context, attrs , 0);
    }

    public KhFileBrowserView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mContext = context;

        mList   = null;
        mAdapter    = null;

        mListener   = null;

        mSelectCnt  = 0;
        mSelectMax  = 0;

        mList = new ArrayList<KhFileBrowserItem>();
        mAdapter = new KhFileBrowserAdapter(mContext, mList);
        this.setAdapter(mAdapter);

        this.setOnItemClickListener(new ItemClickListenr());
    }

    public void setonFileBrowserListener(onFileBrowserListener l) {
        mListener = l;
    }

    public void setSelectEnable() {
        mAdapter.setSelectMode(SELECT.ENABLE);
    }

    public void setSelectDisable() {
        mAdapter.setSelectMode(SELECT.DISABLE);
    }

    public void setSelectAll(boolean b) {
        for(KhFileBrowserItem item : mList) {
            if(item.getType() == TYPE.UNKNOWN || item.getType() == TYPE.IMAGE || item.getType() == TYPE.VIDEO) {
                item.setSelect(b);
            }
        }
        if(b) {
            mSelectCnt = mSelectMax;
        } else {
            mSelectCnt = 0;
        }
        mAdapter.notifyDataSetChanged();
//        if(mListener != null) mListener.onUpdate();
    }

    public void setSelect(ArrayList<String> list) {
        for(String tmp : list) {
            for(KhFileBrowserItem item : mList) {
                if(item.getPath().equals(tmp)) {
                    item.setSelect(true);
                    break;
                }
            }
        }
        mAdapter.notifyDataSetChanged();
    }

    public void setArrowVisble(int visible) {
        mAdapter.setArrowVisible(visible);
    }

    public boolean isSelectAll() {
        if(mSelectMax > 0 && mSelectCnt == mSelectMax) {
            return true;
        }
        return false;
    }

    public int getSelectCount() {
        return mSelectCnt;
    }

    public int getFileSelectMax() {
        return mSelectMax;
    }

    public ArrayList<String> getSelectList() {
        ArrayList<String> selectList = new ArrayList<String>();

        for(KhFileBrowserItem item : mList) {
            if(item.getSelect()) {
                selectList.add(item.getPath());
            }
        }
        return selectList;
    }

    public void add(ArrayList<String> list) {
        mSelectMax += _add(list, FLAG_FOLDER | FLAG_FILE);
    }

    public void refresh(ArrayList<String> list) {
        mList.clear();
        mSelectMax = _add(list, FLAG_FOLDER | FLAG_FILE);
    }

    public void refresh(String path) {
        mSelectMax = _refresh(path, FLAG_FOLDER_UP | FLAG_FOLDER | FLAG_FILE);
    }

    public void refreshOnlyFolder(String path) {
        mSelectMax = _refresh(path, FLAG_FOLDER_UP | FLAG_FOLDER);
    }

    public void refreshOnlyFile(String path) {
        mSelectMax = _refresh(path, FLAG_FILE);
    }

    private int _refresh(String path, int flag) {
        mList.clear();
        mSelectCnt = 0;

        if((flag & FLAG_FOLDER) == FLAG_FOLDER) {
            Map<String, File> externalLocations = KhExternalStorage.getAllStorageLocations();
            mSdCard = externalLocations.get(KhExternalStorage.SD_CARD).getPath();
            mExtsdCard = null;
            if(externalLocations.size() > 1) {
                mExtsdCard = externalLocations.get(KhExternalStorage.EXTERNAL_SD_CARD).getPath();
            }
            mRoot = mSdCard.substring(0, mSdCard.lastIndexOf(File.separator));
            if(path.equals(mRoot)) {
                mList.add(new KhFileBrowserItem(mSdCard, TYPE.SDCARD));
                if(mExtsdCard != null) {
                    mList.add(new KhFileBrowserItem(mExtsdCard, TYPE.EXTSDCARD));
                }
                mAdapter.notifyDataSetChanged();
                return mList.size();
            }
        }

        return _add(path, flag);

    }

    private int _add(String path, int flag) {
        File[] files = new File(path).listFiles();

        ArrayList<String> sortfolder = new ArrayList<String>();
        ArrayList<String> sortfile = new ArrayList<String>();

        if(files != null) {
            for(File file: files) {
                if(file.isDirectory() && !file.getName().startsWith(".")) {
                    sortfolder.add(file.getPath());
                } else if(file.isFile()) {
                    sortfile.add(file.getPath());
                }
            }
        }

        if((flag & FLAG_FOLDER_UP) == FLAG_FOLDER_UP) {
            int separatorIndex = path.lastIndexOf(File.separator);
            if(separatorIndex > 0) {
                mList.add(new KhFileBrowserItem(path.substring(0, separatorIndex), TYPE.UP));
            }
        }

        return _add(sortfolder, sortfile, flag);
    }

    private int _add(ArrayList<String> list, int flag) {
        ArrayList<String> sortfolder = new ArrayList<String>();
        ArrayList<String> sortfile = new ArrayList<String>();

        for(String path : list) {
            File file = new File(path);
            if(file.exists()) {
                if(file.isDirectory() && !file.getName().startsWith(".")) {
                    sortfolder.add(file.getPath());
                } else if(file.isFile()) {
                    sortfile.add(file.getPath());
                }
            }
        }

        return _add(sortfolder, sortfile, flag);
    }

    private int _add(ArrayList<String> folder, ArrayList<String> file, int flag) {
        int addCnt = 0;

        if((flag & FLAG_FOLDER) == FLAG_FOLDER) {
            Collections.sort(folder, String.CASE_INSENSITIVE_ORDER);
            for(String tmp: folder) {
                mList.add(new KhFileBrowserItem(tmp, TYPE.FOLDER));
                addCnt++;
            }
        }

        if((flag & FLAG_FILE) == FLAG_FILE) {
            Collections.sort(file, String.CASE_INSENSITIVE_ORDER);
            for(String tmp: file) {
                mList.add(new KhFileBrowserItem(tmp, KhFileBrowserItem.getType(tmp)));
                addCnt++;
            }
        }
        mAdapter.notifyDataSetChanged();

        return addCnt;
    }

    private class ItemClickListenr implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
            KhFileBrowserItem item = (KhFileBrowserItem) adapterview.getItemAtPosition(i);

            if(item.getType() == TYPE.UP) {
                KhLog.i("KhFileBrowserView : Click - UP");
                if(mListener != null) mListener.onClick(item);
            } else if(item.getType() == TYPE.SDCARD) {
                KhLog.i("KhFileBrowserView : Click - SDCARD");
                if(mListener != null) mListener.onClick(item);
            } else if(item.getType() == TYPE.EXTSDCARD) {
                KhLog.i("KhFileBrowserView : Click - EXTSDCARD");
                if(mListener != null) mListener.onClick(item);
            } else if(item.getType() == TYPE.FOLDER) {
                KhLog.i("KhFileBrowserView : Click - FOLDER");
                if(mListener != null) mListener.onClick(item);
            } else if(mAdapter.getSelectMode() == SELECT.DISABLE) {
                KhLog.i("KhFileBrowserView : Click - File");
                if(mListener != null) mListener.onClick(item);
            } else if(mAdapter.getSelectMode() == SELECT.ENABLE) {
                KhLog.i("KhFileBrowserView : Click - Select");
                mSelectCnt += mAdapter.doSelect(item, view);
                if(mListener != null) mListener.onClick(item);
            }
        }
    }
}
